// 

import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess, history, useModel } from '@umijs/max';
import { DataNode } from 'antd/es/tree';
import { Button, message, Modal, Dropdown, FormInstance, Space, Switch, Tag } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, DownOutlined } from '@ant-design/icons';
import UpdateForm from './components/InspectionForm';
import dayjs from 'dayjs';
import {getInspectionList, removeInspection, addInspection, updateInspection ,} from '@/services/manage/inspection';

const { confirm } = Modal;

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.Manage.Inspection) => {
  const hide = message.loading('正在添加');
  try {
    const resp = await addInspection({ ...fields });
    hide();
    if (resp.code === 200) {
      message.success('添加成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Manage.Inspection) => {
  const hide = message.loading('正在更新');
  try {
    const resp = await updateInspection(fields);
    hide();
    if (resp.code === 200) {
      message.success('更新成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.Manage.Inspection[]) => {
  // console.log(selectedRows);  
  const hide = message.loading('正在删除');  
  if (!selectedRows) return true;
  try {
    const resp = await removeInspection(selectedRows.map((row) => row.taskId).filter((id): id is number => id !== undefined))
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.Manage.Inspection) => {
  console.log(selectedRow);  
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.taskId];
    console.log(params)
    const resp = await removeInspection(params.filter((id): id is number => id !== undefined));
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 导出数据
 *
 *
 */
// const handleExport = async () => {
//   const hide = message.loading('正在导出');
//   try {
//     await exportRole();
//     hide();
//     message.success('导出成功');
//     return true;
//   } catch (error) {
//     hide();
//     message.error('导出失败，请重试');
//     return false;
//   }
// };


const InspectionTable: React.FC = () => {

  const [messageApi, contextHolder] = message.useMessage();
  const formTableRef = useRef<FormInstance>();

  const [modalVisible, setModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Manage.Inspection>();
  const [selectedRows, setSelectedRows] = useState<API.Manage.Inspection[]>([]);
  const [pageSize, setPageSize] = useState(10);
  const [InspectionTypes, setInspectionTypes] = useState<string[]>([]);

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 

  const access = useAccess();

  const [openModal, setOpenModal] = useState(false);
  const [currentRoute, setCurrentRoute] = useState<string>('');
  const [routePoints, setRoutePoints] = useState<string[]>([]);

  /** 国际化配置 */
  const intl = useIntl();
//   //获取故障类型
//   const InspectionTypes = async () => { 
//     const types = await getInspectionNames()
//     console.log('types', types);   
//     const typeList = types?.rows
//     setInspectionTypes(typeList)
//   }
  const taskStatusMap: Record<number, { color: string; text: string }> = {
    0: { color: 'gray', text: '未开始' },
    1: { color: 'blue', text: '进行中' },
    2: { color: 'green', text: '已完成' },
    3: { color: 'red', text: '中断' },
  };
  type RouteRecord = {
    id: number;
    routeName: string;
    points: string[];
  };

  const mockData: RouteRecord[] = [
    {
      id: 1,
      routeName: '路线1',
      points: ['点位 A1', '点位 A2', '点位 A3'],
    },
    {
      id: 2,
      routeName: '路线4',
      points: ['点位 B1', '点位 B2'],
    },
    {
      id: 3,
      routeName: '路线7',
      points: [],
    },
  ];


  useEffect(() => {
    // InspectionTypes()
  }, []);


 const columns: ProColumns<API.Manage.Inspection>[] = [
    {
      title: '任务编号',
      dataIndex: 'taskId',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
      sorter: (a, b) => (a.taskId ?? 0) - (b.taskId ?? 0),
      defaultSortOrder: 'descend',
    },
    {
      title: '任务名称',
      dataIndex: 'taskName',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '任务类型',
      dataIndex: 'taskType',
      align: 'center',
      valueType: 'text',
      valueEnum:{
        "例行": { text: '例行', status: 'Default' },
        "临时": { text: '临时', status: 'Processing' },
      },
      render: (_, record) => {
        const { taskType } = record;
        return <Tag color={taskType === '例行' ? 'blue' : 'orange'}>{taskType}</Tag>;
      },
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '设备编号',
      dataIndex: 'deviceNum',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '任务状态',
      dataIndex: 'taskStatus',
      align: 'center',
      valueType: 'select',
      valueEnum: taskStatusMap,
      render: (_, record) => {
        const { taskStatus } = record;
        const status = taskStatusMap[taskStatus] || { color: 'default', text: '未知' };
        return <Tag color={status.color}>{status.text}</Tag>;
      },
    },
    {
      title: '路线名称',
      dataIndex: 'routeName',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
      // render: (_, record) => (
      //   <a
      //     onClick={() => {
      //       setCurrentRoute(record.routeName);
      //       const route = mockData.find((route) => route.routeName === record.routeName);
      //       setRoutePoints(route?.points || []);
      //       setOpenModal(true);
      //     }}
      //     style={{ color: 'white', cursor: 'pointer', textDecoration: 'underline' } }
      //   >
      //     {record.routeName}
      //   </a>
      // )
      
    },
    {
      title: '计划开始时间',
      dataIndex: 'planStart',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.planStart 
          ? dayjs(record.planStart).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: '计划结束时间',
      dataIndex: 'planEnd',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.planEnd 
          ? dayjs(record.planEnd).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: '实际开始时间',
      dataIndex: 'actualStart',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.actualStart 
          ? dayjs(record.actualStart).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEnd',
      align: 'center',
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.actualEnd 
          ? dayjs(record.actualEnd).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: '发起人',
      dataIndex: 'initiator',
      align: 'center',
      valueType: 'text',
      hideInSearch: true,
    },
    {
          title: "操作" ,
          dataIndex: 'option',
          width: '220px',
          align: 'center',
          valueType: 'option',
          render: (_, record) => [
            <Button
              type="link"
              size="small"
              style={{ color: '#3C9AE8' }}
              icon=<EditOutlined />
              hidden={!access.hasPerms('inspection:patrolTask:edit')}
              onClick={async() => {          
                if (record.taskStatus === 0||record.taskStatus ===3) {
                  const recordAdd = { ...record }; // 创建 record 的副本
                  recordAdd.taskStatus = 1; // 设置处理状态为处理中     
                  recordAdd.actualStart = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 设置处理时间为当前时间  
                  console.log(recordAdd);                      
                  await updateInspection(recordAdd).then((res) => {
                    if (res.code === 200) {
                      message.success('开始巡检');
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    } else {
                      message.warning(res.msg);
                    }
                  })
                }
                else if(record.taskStatus === 1) {
                  message.warning('该巡检正在进行中，请勿重复点击！');
                }
                else if(record.taskStatus === 2) {
                  message.warning('该巡检已完成，请勿重复点击！');
                }
              }}
            >
              开始
            </Button>,
            <Button
              type="link"
              size="small"
              style={{ color: 'green' }}
              icon=<EditOutlined />
              hidden={!access.hasPerms('inspection:patrolTask:edit')}
              onClick={async() => {
                if (record.taskStatus === 0) {
                  message.warning('该巡检未处理，请先开始巡检！');
                }
                else if (record.taskStatus === 1) {
                  const recordAdd = { ...record }; // 创建 record 的副本
                  recordAdd.taskStatus = 2; // 设置处理状态为已处理
                  recordAdd.actualEnd = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 设置处理时间为当前时间                   
                  await updateInspection(recordAdd).then((res) => {
                    if (res.code === 200) {
                      message.success(' 巡检完成');
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    } else {
                      message.warning(res.msg);
                    }
                  })
                }
                else if(record.taskStatus === 2) {
                  message.warning('该巡检已完成，请勿点击！');
                }
                else if(record.taskStatus === 3) {
                  // 如果任务状态是"中断"，弹出确认对话框
                  Modal.confirm({
                    title: '恢复中断任务',
                    content: '该任务已中断，是否将其标记为完成？',
                    okText: '确认完成',
                    cancelText: '取消',
                    onOk: async () => {
                      const recordAdd = { ...record }; // 创建 record 的副本
                      recordAdd.taskStatus = 2; // 设置处理状态为已完成
                      recordAdd.actualEnd = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 设置完成时间为当前时间
                      
                      await updateInspection(recordAdd).then((res) => {
                        if (res.code === 200) {
                          message.success('已将中断任务标记为完成');
                          if (actionRef.current) {
                            actionRef.current.reload();
                          }
                        } else {
                          message.warning(res.msg);
                        }
                      });
                    },
                    onCancel() {
                      message.info('操作已取消');
                    },
                  });
                }
              }}
            >
              完成
            </Button>, 
            <Button
              type="link"
              size="small"
              style={{ color: 'orange' }}
              icon=<EditOutlined />
              hidden={!access.hasPerms('inspection:patrolTask:edit')}
              onClick={async() => {
                if (record.taskStatus === 0||record.taskStatus === 2) {
                  message.warning('无法中断！');
                }
                else if (record.taskStatus === 1) {
                  const recordAdd = { ...record }; // 创建 record 的副本
                  recordAdd.taskStatus = 3; // 设置处理状态为已处理    
                  recordAdd.actualEnd = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 设置处理时间为当前时间              
                  await updateInspection(recordAdd).then((res) => {
                    if (res.code === 200) {
                      message.success(' 处理结束成功');
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    } else {
                      message.warning(res.msg);
                    }
                  })
                }
                else if(record.taskStatus === 3) {
                  message.warning('该巡检已中断，请勿重复点击！');
                }
              }}
            >
              中断
            </Button>, 
            <Button
              type="link"
              size="small"
              danger
              key="delete"
              icon=<DeleteOutlined />
              hidden={!access.hasPerms('inspection:asset:removes')}
              onClick={async () => {
                Modal.confirm({
                  title: '删除',
                  content: '确定删除该资产吗？',
                  okText: '确认',
                  cancelText: '取消',
                  onOk: async () => {
                    const success = await handleRemoveOne(record);
                    if (success) {
                      if (actionRef.current) {
                        actionRef.current.reload();
                      }
                    }
                  },
                });
              }}
            >
              删除
            </Button>,
          ],
        },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.Manage.Inspection>
          headerTitle='查询巡检表格'
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="taskId"
          key="InspectionList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('inspection:patrolTask:add')}
              onClick={async () => {
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
            <Button
              type="primary"
              key="remove"
              danger
              hidden={selectedRows?.length === 0 || !access.hasPerms('inspection:InspectionMain:remove')}
              onClick={async () => {
                Modal.confirm({
                  title: '是否确认删除所选数据项?',
                  icon: <ExclamationCircleOutlined />,
                  content: '请谨慎操作',
                  async onOk() {
                    const success = await handleRemove(selectedRows);
                    if (success) {
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                  onCancel() { },
                });
              }}
            >
              <DeleteOutlined />
              <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
            </Button>,
            // <Button
            //   type="primary"
            //   key="export"
            //   hidden={!access.hasPerms('system:role:export')}
            //   onClick={async () => {
            //     handleExport();
            //   }}
            // >
            //   <PlusOutlined />
            //   <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            // </Button>,
          ]}
          request={(params) => {
            const { current, ...rest } = params;
            const queryParams = {
              pageNum: current,       // 将 current 映射为 pageNum
              pageSize: params.pageSize,
              ...rest,
            };            
            return getInspectionList(queryParams as API.Manage.InspectionParams).then((res) => {
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            });
          }}
          
          columns={columns}
          columnsState={{
            persistenceKey: 'inspection-table',
            persistenceType: 'localStorage',
            defaultValue: {
              planStart: {show: false  }, // ✅ 默认隐藏，但用户可手动勾选
              planEnd: {show: false  },
              actualStart: {show: false  },
              actualEnd: {show: false  }
            },
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
          pagination={{
            pageSize,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
          }}
        />
      </div>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            key="remove"
            danger
            hidden={!access.hasPerms('inspection:InspectionMain:remove')}
            onClick={async () => {
              Modal.confirm({
                title: '删除',
                content: '确定删除该项吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemove(selectedRows);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;
          // success = await handleUpdate({ ...values } as API.Manage.Inspection);
          console.log(values);          
          success = await handleAdd({ ...values } as unknown as API.Manage.Inspection)
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
      />
      <Modal
        open={openModal}
        title={`「${currentRoute}」的点位信息`}
        onCancel={() => setOpenModal(false)}
        footer={null}
      >
        {routePoints.length ? (
          <ul style={{ paddingLeft: 20 }}>
            {routePoints.map((point, index) => (
              <li key={index}>{point}</li>
            ))}
          </ul>
        ) : (
          <p>暂无点位数据</p>
        )}
      </Modal>
    </PageContainer>    
  );
};

export default InspectionTable;